package com.xsqf.jt808.controller;

import com.xsqf.jt808.common.config.ChannelManager;
import com.xsqf.jt808.common.config.JT808Const;
import com.xsqf.jt808.common.vo.DataPacket;
import com.xsqf.jt808.common.vo.ResultVo;
import com.xsqf.jt808.common.vo.req.server.ParameterSetting;
import com.xsqf.jt808.common.vo.req.server.PassthroughPack;
import com.xsqf.jt808.common.vo.resp.CommonResp;
import com.xsqf.jt808.common.vo.resp.PositionReply;
import com.xsqf.jt808.netty.handler.PositionHandler;
import com.xsqf.jt808.netty.handler.TerminalComRespHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPromise;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

import static com.xsqf.jt808.common.vo.ResultVo.CODE_FAIL;
import static com.xsqf.jt808.common.vo.ResultVo.CODE_SUCCESS;
import static com.xsqf.jt808.common.vo.req.server.PassthroughPack.Custom;

/**
 * TerminalController
 *
 * @author
 * @date 2020/5/26 15:14
 */
@Api(tags = {"终端控制"})
@RestController
@RequestMapping(value = "/api/terminal")
public class TerminalController {

    @Autowired
    private ChannelManager channelManager;

    @Autowired
    private PositionHandler positionHandler;
    @Autowired
    private TerminalComRespHandler terminalComRespHandler;

    @ApiOperation(value = "位置信息查询")
    @PostMapping(value = "{terminalId}/position")
    public ResultVo findPosition(@PathVariable("terminalId") String terminalId) {

        DataPacket dataPacket = new DataPacket();
        dataPacket.getHeader().setMsgId(JT808Const.SERVER_MSG_FIND_LOCATION);
        dataPacket.getHeader().setTerminalPhone(terminalId);

        ChannelPromise promise = positionHandler.sendMessage(dataPacket);
        try {
            promise.await(3, TimeUnit.SECONDS);
            PositionReply response = positionHandler.getResponse();

            return new ResultVo(CODE_SUCCESS, "成功！", response);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return new ResultVo(CODE_FAIL, "失败！", e);
        }
    }


    @ApiOperation(value = "设置终端参数")
    @PostMapping(value = "{terminalId}/setParameters")
    public ResultVo setParameters(@PathVariable("terminalId") String terminalId, @RequestBody ParameterSetting parameterSetting) {

        Channel channel = channelManager.get(terminalId);
        if (channel != null && channel.isWritable()) {
            parameterSetting.getHeader().setMsgId(JT808Const.SERVER_MSG_SET_TERNIMAL_PARAMETER);
            parameterSetting.getHeader().setTerminalPhone(terminalId);

            ChannelPromise promise = terminalComRespHandler.sendMessage(parameterSetting);
            try {
                promise.await(3, TimeUnit.SECONDS);
                CommonResp response = terminalComRespHandler.getResponse();

                return new ResultVo(CODE_SUCCESS, "成功！", response);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return new ResultVo(CODE_FAIL, "失败！", e);
            }

        }
        return new ResultVo(CODE_FAIL, "失败！");

    }


    /**
     * 用户设置服务器IP + 端口号，参数仅需->content：IP 123.13.168.11 9230（注：中间有空格）
     * @param terminalId
     * @param passthroughPack
     * @return
     */
    @ApiOperation(value = "数据下行透传")
    @RequestMapping(value = "{terminalId}/passthrough", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo passthrough(@PathVariable("terminalId") String terminalId, @RequestBody PassthroughPack passthroughPack) {

        Channel channel = channelManager.get(terminalId);
        if (channel != null && channel.isWritable()) {
            passthroughPack.getHeader().setMsgId(JT808Const.SERVER_MSG_DATA_PASSTHROUGH);
            passthroughPack.getHeader().setTerminalPhone(terminalId);
            passthroughPack.setType(Custom); //用户自定义
            channel.writeAndFlush(passthroughPack);

            return new ResultVo(CODE_SUCCESS, "成功！");
        }
        return new ResultVo(CODE_FAIL, "失败！");
    }


//    @ApiOperation(value = "查询终端参数")
//    @PostMapping(value = "{terminalId}/findParameters")
//    public ResultVo findParameters(@PathVariable("terminalId") String terminalId) {
//
//        DataPacket dataPacket = new DataPacket();
//        dataPacket.getHeader().setMsgId(JT808Const.SERVER_MSG_GET_TERNIMAL_PARAMETER);
//        dataPacket.getHeader().setTerminalPhone(terminalId);
//
//        channelManager.get(terminalId).writeAndFlush(dataPacket);
//
    //  接收终端返回消息
//
//        return null;
//
//
//    }

//    @ApiOperation(value = "查询指定终端参数")
//    @PostMapping(value = "{terminalId}/findParametersSome")
//    public ResultVo findParametersSome(@PathVariable("terminalId") String terminalId, @ApiParam("终端参数ID列表") @RequestBody Integer[] idList) {
//
//        ParameterQuerySome parameterQuerySome = new ParameterQuerySome();
//        for (Integer id : idList) {
//            parameterQuerySome.addTerminalParameter(new TerminalParameter(id));
//        }
//        parameterQuerySome.getHeader().setMsgId(JT808Const.SERVER_MSG_GET_APPOINT_TERNIMAL_PARAMETER);
//        parameterQuerySome.getHeader().setTerminalPhone(terminalId);
//        channelManager.get(terminalId).writeAndFlush(parameterQuerySome);
//
//        return new ResultVo(CODE_SUCCESS, "成功！");
//
//    }

//    @ApiOperation(value = "终端控制")
//    @PostMapping(value = "{terminalId}/control/terminal")
//    public ResultVo terminalControl(@PathVariable("terminalId") String terminalId, @RequestBody TerminalControl terminalControl) {
//
//        Channel channel = channelManager.get(terminalId);
//        if (channel != null && channel.isWritable()) {
//            terminalControl.getHeader().setMsgId(JT808Const.SERVER_MSG_CONTROL_TERNIMAL);
//            terminalControl.getHeader().setTerminalPhone(terminalId);
//            channel.writeAndFlush(terminalControl);
//
//            return new ResultVo(CODE_SUCCESS, "成功！");
//        }
//        return new ResultVo(CODE_FAIL, "失败！");
//
//    }

//    @ApiOperation(value = "查询终端属性")
//    @PostMapping(value = "{terminalId}/findAttribute")
//    public ResultVo findAttribute(@PathVariable("terminalId") String terminalId) {
//
//        AttributeQuery attributeQuery = new AttributeQuery();
//        attributeQuery.getHeader().setMsgId(JT808Const.SERVER_MSG_GET_TERNIMAL_ATTRIBUTE);
//        attributeQuery.getHeader().setTerminalPhone(terminalId);
//        channelManager.get(terminalId).writeAndFlush(attributeQuery);
//
////        接收终端返回消息
//
//        return new ResultVo(CODE_SUCCESS, "成功！");
//
//    }

}
